package Offer;

import java.util.ArrayList;
import java.util.Arrays;

/*
* 序列化二叉树
*
* */
public class Offer37serialize {
    // Encodes a tree to a single string.
    public String serialize(TreeNode root) {
        return reserialize(root,"");
    }

    private String reserialize(TreeNode root,String s) {
        if(root==null){
            s+="null,";
        }else{
            s+=String.valueOf(root.val)+",";
            reserialize(root.left,s);
            reserialize(root.right,s);
        }
        return s;
    }

    // Decodes your encoded data to tree.
    public TreeNode deserialize(String data) {
        String[] split = data.split(",");
        ArrayList<String> list = new ArrayList<>(Arrays.asList(split));
        return redeserialize(list);

    }

    private TreeNode redeserialize(ArrayList<String> list) {
        if(list.get(0)=="null"){
            list.remove(0);
            return null;
        }
        TreeNode root = new TreeNode(Integer.valueOf(list.get(0)));
        list.remove(0);
        root.left=redeserialize(list);
        root.right=redeserialize(list);
        return root;
    }
}
